<!-- 表单渲染 -->
<template>
  <div class="renderFormCont">
    <div v-if="BaseFormData && BaseFormData.formTitle" class="title">
      {{ BaseFormData.formTitle || '' }}
    </div>
    <div v-if="formData" class="formCont">
      <t-form
        ref="formValidatorStatus"
        :data="formData"
        :rules="rules"
        :label-width="100"
        width="100%"
        style="width: 100%; display: flex; flex-wrap: wrap"
        @reset="onReset"
        @submit="onSubmit"
      >
        <t-form-item
          v-for="item in renderFormData"
          v-show="!item.data.isShow"
          :key="item.id"
          :label-width="
            !item.data.isShowTitle ? (item.data.isMust ? '10px' : 0) : '100px'
          "
          :label="item.data.isShowTitle ? `${item.data.title}：` : ''"
          :name="`${item.id}`"
          :style="{ width: `${item.data.width ? item.data.width : 100}%` }"
        >
          <!-- 单行文本 -->
          <t-input
            v-if="item.type === 'input'"
            v-model="formData[`${item.id}`]"
            :placeholder="item.placeholder"
            :showLimitNumber="item.data.isStatistics"
            :defaultValue="item.defaultValue"
            :maxlength="Number(item.data.maxLength)"
            :minlength="Number(item.data.minLength)"
            :disabled="item.data.isReadOnly"
          ></t-input>
          <!-- 多行文本 -->
          <t-textarea
            v-if="item.type === 'textArea'"
            v-model="formData[`${item.id}`]"
            :placeholder="item.placeholder"
            :maxcharacter="Number(item.data.maxLength)"
            :showLimitNumber="item.data.isStatistics"
          />
          <!-- 单选 -->
          <t-radio-group
            v-if="item.type === 'radio'"
            v-model="formData[`${item.id}`]"
            :defaultValue="item.data.defaultValue"
            :style="{ display: 'flex', 'flex-direction': item.data.direction }"
          >
            <t-radio
              v-for="it in item.data.titlab"
              :key="it"
              :label="it"
              :value="it"
            />
          </t-radio-group>
          <!-- 多选 -->
          <t-checkbox-group
            v-if="item.type === 'checkbox'"
            :value="formData[`${item.id}`] || []"
            :defaultValue="item.data.defaultValue || []"
            :style="{ display: 'flex', 'flex-direction': item.data.direction }"
            :max="Number(item.data.maxLength) || Infinity"
            @change="checkboxHandle"
            @click="checkboxClick(item)"
          >
            <t-checkbox
              v-for="(it, ind) in item.data.titlab"
              :key="ind"
              :label="it"
              :value="it"
            />
          </t-checkbox-group>
          <!-- 下拉框 -->
          <t-select
            v-if="item.type === 'select'"
            :value="formData[`${item.id}`]"
            placeholder="请选择"
            :multiple="item.data.maxLength > 1"
            :max="Number(item.data.maxLength) || 100"
            size="small"
            class="selectCont"
            @click="selectClick(item)"
            @change="defaultValueHandel"
          >
            <t-option
              v-for="it in item.data.titlab"
              :key="it"
              :label="it"
              :value="it"
            />
          </t-select>
          <!-- 开关 -->
          <t-switch
            v-if="item.type === 'switch'"
            v-model="formData[`${item.id}`]"
          />
          <!-- 评分 -->
          <t-rate
            v-if="item.type === 'rate'"
            v-model="formData[`${item.id}`]"
            allowHalf
            size="20px"
          ></t-rate>
          <!-- 滑块 -->
          <t-slider
            v-if="item.type === 'slider'"
            v-model="formData[`${item.id}`]"
            :max="item.data.maxValue"
            :min="item.data.minValue"
            :step="item.data.step"
            size="small"
          />
          <!-- 日期选择器 -->
          <t-date-picker
            v-if="item.type === 'timeSelect'"
            v-model="formData[`${item.id}`]"
            :mode="
              item.data.dateType === 'dateTime' ? 'date' : item.data.dateType
            "
            :disableDate="disableDateHandle(item)"
            clearable
            :enable-time-picker="item.data.dateType === 'dateTime'"
          />
          <!-- 日期区间 -->
          <t-date-range-picker
            v-if="item.type === 'dateArea'"
            v-model="formData[`${item.id}`]"
            clearable
            size="small"
            :mode="
              item.data.dateType === 'dateTime' ? 'date' : item.data.dateType
            "
            :disableDate="dateAreadisableDateHandle(item)"
            :enable-time-picker="item.data.dateType === 'dateTime'"
          />
          <!-- 数字输入框 -->
          <t-input-number
            v-if="item.type === 'number'"
            v-model="formData[`${item.id}`]"
            :max="item.data.maxValue || Infinity"
            :min="item.data.minValue || -Infinity"
            placeholder="请输入默认值"
          >
            <template #label
              ><span>{{ item.data.prefix }}</span></template
            >
          </t-input-number>
          <!-- 附件 -->
          <!-- 图片 -->
          <!-- 位置 -->
          <!-- 省市区 -->
          <!-- 分割线 -->
          <!-- 按钮 -->
          <!-- 部门 -->
          <!-- 人员 -->
        </t-form-item>
      </t-form>
    </div>
    <!-- <div v-eles>
      表单生成中...
    </div> -->
    <div class="fx" style="margin-top: 20px">
      <div class="bt" style="margin: 20px" @click="onSubmit">数据提交</div>
      <div class="bt" style="margin: 20px" @click="cacheHandle">数据暂存</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useRoute } from 'vue-router'
import { useFormData } from '@/store'
import { formDataes } from '@/api/form'

const store = useFormData()
// 禁用日期 - 日期选择
const disableDateHandle = (item) => {
  const data = {
    before: item.data.minValue,
    after: item.data.maxValue
  }
  for (const key in data) {
    if (!data[key]) {
      data[key] = undefined
    }
  }
  return JSON.parse(JSON.stringify(data))
}
// 禁用日期 - 日期区间 - 时间区间如果是周的话 需要把禁用的日期处理一下
const dateAreadisableDateHandle = (item) => {
  const data = {
    before:
      item.data.dateType === 'week'
        ? item.data.disableDaySt
        : item.data.minValue,
    after:
      item.data.dateType === 'week'
        ? item.data.disableDayLt
        : item.data.maxValue
  }
  for (const key in data) {
    if (!data[key]) {
      data[key] = undefined
    }
  }
  return JSON.parse(JSON.stringify(data))
}
// 动态渲染表单的 数据 - 来源于设计表单的数据
const BaseFormData = ref()
const renderFormData = ref()
const formValidatorStatus = ref()
// 暂时做的模拟数据 - 目前是没用了
const data = reactive({
  baseFormData: {
    icon: 'chart-bubble',
    color: 'var(--color-main)',
    fromType: '0',
    formTitle: '测试表单',
    groupId: '1',
    formDescribe: 'asdfasdfsadf'
  },
  formData: [
    {
      page: 1,
      type: 1,
      data: [
        {
          type: 'input',
          lab: '单行输入框',
          icon: 'icon_danhang2x',
          data: {
            title: '单行输入框',
            placeholder: '请输入',
            width: 100,
            defaultWidth: '1',
            minLength: '',
            maxLength: '',
            isReadOnly: false,
            isStatistics: false,
            isShowTitle: true,
            isMust: false,
            isOnly: false,
            inputType: '',
            errorPrompt: '',
            defaultValue: '默认值的合并Input初始数据'
          },
          id: 51390394593489
        },
        {
          type: 'textArea',
          lab: '多行输入框',
          icon: 'icon_duohang2x',
          data: {
            title: '多行输入框',
            placeholder: '请输入',
            width: 100,
            minLength: '',
            maxLength: '',
            isReadOnly: false,
            isStatistics: false,
            isShow: false,
            isShowTitle: true,
            isMust: false,
            defaultValue: ''
          },
          id: 26410724149313
        },
        {
          type: 'radio',
          lab: '单选框',
          icon: 'icon_danxuankuang2x',
          data: {
            title: '单选框',
            placeholder: '请选择',
            width: 100,
            isShowTitle: true,
            isShow: false,
            isMust: false,
            direction: 'column',
            defaultValue: '',
            dataType: 'static',
            titlab: ['选项一', '选项二', '选项三', '选项四'],
            dynamicData: {
              url: '',
              method: '',
              key: '',
              value: ''
            }
          },
          id: 48583325571289
        },
        {
          type: 'checkbox',
          lab: '多选框',
          icon: 'icon_xialaxuanze2x',
          data: {
            title: '多选框',
            width: 100,
            isShowTitle: true,
            isShow: false,
            isMust: false,
            isExclude: false,
            excludeOptions: [],
            direction: 'column',
            minValue: 0,
            maxValue: 0,
            dataType: 'static',
            titlab: ['选项1', '选项2', '选项3', '选项4'],
            dynamicData: {
              url: '',
              method: '',
              key: '',
              value: ''
            }
          },
          id: 50578424274878
        },
        {
          type: 'select',
          lab: '下拉选择框',
          icon: 'icon_xialaxuanze2x',
          data: {
            title: '下拉选择框',
            placeholder: '请选择',
            width: 100,
            isShowTitle: true,
            isShow: false,
            isMust: false,
            titlab: ['选项1', '选项2', '选项3', '选项4']
          },
          id: 89815391264271
        },
        {
          type: 'timeSelect',
          lab: '日期选择器',
          icon: 'icon_shijianxuanze2x',
          data: {
            title: '日期选择器',
            width: 100,
            placeholder: '选择日期',
            defaultWidth: 100,
            minValue: '',
            maxValue: '',
            isReadOnly: false,
            isShowTitle: true,
            isShow: true,
            defaultValueDay: false,
            isMust: false,
            isOnly: false,
            defaultValue: '',
            dateType: 'day',
            dateFormat: 'yyyy-MM-dd'
          },
          id: 18589273607518
        },
        {
          type: 'number',
          lab: '数字输入框',
          icon: 'icon_shuzi2x',
          data: {
            title: '数字输入框',
            placeholder: '请选择',
            width: 100,
            minValue: '',
            maxValue: '',
            floatNum: '',
            prefix: '',
            defaultValue: '',
            isReadOnly: false,
            isShowTitle: true,
            isShow: false,
            isMust: false
          },
          id: 3142377847829
        },
        {
          type: 'dateArea',
          lab: '日期区间',
          icon: 'icon_shijianqujian2x',
          data: {
            title: '日期区间',
            startTitle: '开始时间',
            endTitle: '结束时间',
            width: 100,
            startTime: '2023.1',
            endTime: '2023.10',
            isReadOnly: false,
            isShowTitle: true,
            isShow: true,
            isMust: false,
            defaultValue: '',
            dateType: 'date',
            dataFormat: 'yyyy-MM-dd'
          },
          id: 43687668828894
        },
        {
          type: 'rate',
          lab: '评分',
          icon: 'icon_pingfen2x',
          data: {
            title: '评分',
            width: 100,
            defaultWidth: '1',
            minValue: 0,
            maxValue: 5,
            isReadOnly: false,
            isShowTitle: true,
            isShow: false,
            isMust: false,
            defaultValue: ''
          },
          id: 39353656926441
        },
        {
          type: 'switch',
          lab: '开关',
          icon: 'icon_kaiguan2x',
          data: {
            title: '开关',
            width: 100,
            defaultWidth: 1,
            openText: '',
            closeText: '',
            isReadOnly: false,
            isShowTitle: true,
            isShow: false,
            isMust: false,
            defaultValue: false
          },
          id: 69884857235284
        },
        {
          type: 'slider',
          lab: '滑块选择',
          icon: 'icon_huakuai2x',
          data: {
            title: '滑块选择',
            minValue: 1,
            maxValue: 100,
            step: 1,
            defaultValue: 50,
            width: 100,
            defaultWidth: 1,
            isReadOnly: false,
            isShowTitle: true,
            isShow: true,
            isMust: false,
            numShow: true
          },
          id: 81266808804140
        }
      ]
    }
  ]
})
const openType = ref('preview') // 'from' 表单正常使用模式,  'preview' 预览模式 不走接口
// 初始化渲染表单
onMounted(() => {
  openType.value = route.query.id ? 'from' : 'preview'
  initDataHandle()
})

const initDataHandle = () => {
  if (openType.value === 'preview') {
    // 使用 pinia 的缓存数据 这个后面做预览使用
    const storeData = store.getSubmitFormData.palyload
    if (storeData) {
      BaseFormData.value = storeData.formDetail.baseFormData // data.baseFormData
      renderFormData.value = storeData.formDetail.formData[0].data //
      formDataInit()
    }
  } else {
    // 下面是和流程通过ifrome进行交互的逻辑
    // if (parent.window) {
    //   // console.log(78,formValidatorStatus.value.offsetWidth, formValidatorStatus.value.clientHeight)
    //   parent.window.postMessage(
    //     { type: 'setSize', width: '500px', height: '800px' },
    //     'http://172.16.43.97:8080/'
    //   )
    // }
    window.addEventListener(
      'message',
      (e) => {
        const data = e.data
        // 来自流程的初始化数据
        if (data.type === 'loadForm') {
          // 初始数据合并到formData里
        }
        // 来自流程的数据提交
        if (data.type === 'submitForm') {
          onSubmit()
        }
        // 来自流程的暂存数据提交
        if (data.type === 'cacheForm') {
          cacheHandle()
        }
      },
      false
    )
    // 初始化数据 - 使用接口数据
    getFromDataDetails()
  }
}

// 下拉的处理 -- start
// 暂存下拉点击选项
const selectItem = ref()
const selectClick = (item) => {
  selectItem.value = item
}
// 选择默认值  这里有两种模式 一种 正常单选下拉 一种多选标签式的
const defaultValueHandel = (val, context) => {
  if (!val) return
  // 多选
  if (
    selectItem.value.data.maxLength !== undefined &&
    Number(selectItem.value.data.maxLength) > 1 &&
    context.trigger === 'check'
  ) {
    selectHandle(val, { current: context.option.value })
  } else {
    formData.value[`${selectItem.value.id}`] = val
  }
}
// 互斥选项处理 - 多选
const selectHandle = (val, context) => {
  const item = selectItem.value
  // 选中
  if (item.data.excludeOptions && item.data.excludeOptions.length > 0) {
    const ind = item.data.excludeOptions.indexOf(context.current)
    // 如果有互斥项已经被选 做标记
    const valInd = formData.value[`${item.id}`].indexOf(context.current)
    // 已经选择了一个互斥项
    if (
      Array.isArray(formData.value[`${item.id}`]) &&
      formData.value[`${item.id}`].length === 1 &&
      item.data.excludeOptions.indexOf(formData.value[`${item.id}`][0]) !== -1
    ) {
      formData.value[`${item.id}`] = [context.current]
      return
    }
    // 互斥项处理 - 互斥选项中没有并且也没有被选中过
    if (ind === -1 && valInd === -1) {
      if (
        Array.isArray(formData.value[`${item.id}`]) &&
        formData.value[`${item.id}`].length === 0
      ) {
        formData.value[`${item.id}`] = [context.current]
      } else {
        formData.value[`${item.id}`].push(context.current)
      }
      // 在互斥选项中有并且已经被选中直接清空
    } else if (ind !== -1 && valInd !== -1) {
      formData.value[`${item.id}`] = []
      // 在互斥选项中有并且没有被选中 直接选中
    } else if (ind !== -1 && valInd === -1) {
      formData.value[`${item.id}`] = [context.current]
    }
  } else {
    formData.value[`${item.id}`] = val
  }
}
// 下拉的处理 -- end

// ifrom交互提交
// const postMessageHandle = (data) => {}
const route = useRoute()
// 获取表单的详情
const getFromDataDetails = async () => {
  const id = route.query.id
  const params = {
    id: 'GET_MY_FORM',
    messageAuth: {
      tenant: 'tenant_hiss',
      currentUser: {
        userId: '1',
        userName: '张三',
        userGroups: ''
      }
    },
    palyload: {
      ids: id, // 'dc0af849c7f98019a6918debe03fcf56',
      query: ''
    }
  }
  await formDataes(params).then((res) => {
    const resData = res.data.res
    const context = JSON.parse(resData[0].context)
    BaseFormData.value = context.baseFormData
    renderFormData.value = context.formData[0].data
    // 默认值的处理
    formDataInit()
  })
}
// 表单数据
const formData = ref({})
// 暂存多选点击选项
const changeItem = ref()
const checkboxClick = (item) => {
  changeItem.value = item
}
// 互斥选项处理 - 多选
const checkboxHandle = (val, context) => {
  const item = changeItem.value
  if (!Array.isArray(formData.value[`${item.id}`])) {
    formData.value[`${item.id}`] = []
  }
  const itData = formData.value[`${item.id}`]
  // 取消选项
  const ckInd = Array.isArray(itData) ? itData.indexOf(context.current) : -1
  if (ckInd !== -1) {
    formData.value[`${item.id}`].splice(ckInd, 1)
    return
  }
  // 选中
  if (item.data.excludeOptions && item.data.excludeOptions.length > 0) {
    const ind = item.data.excludeOptions.indexOf(context.current)
    // 如果有互斥项已经被选 做标记
    const valInd = itData.indexOf(context.current)
    // 已经选择了一个互斥项
    if (
      Array.isArray(itData) &&
      itData.length === 1 &&
      item.data.excludeOptions.indexOf(itData[0]) !== -1
    ) {
      formData.value[`${item.id}`] = [context.current]
      return
    }
    // 互斥项处理 - 互斥选项中没有并且也没有被选中过
    if (ind === -1 && valInd === -1) {
      if (Array.isArray(itData) && itData.length === 0) {
        formData.value[`${item.id}`] = [context.current]
      } else {
        formData.value[`${item.id}`].push(context.current)
      }
      // 在互斥选项中有并且已经被选中直接清空
    } else if (ind !== -1 && valInd !== -1) {
      formData.value[`${item.id}`] = []
      // 在互斥选项中有并且没有被选中 直接选中
    } else if (ind !== -1 && valInd === -1) {
      formData.value[`${item.id}`] = [context.current]
    }
  } else {
    formData.value[`${item.id}`] = val
  }
}
// input 效验
// 表单效验 - 动态生成的
const rules = computed(() => {
  const rulesData = {}
  if (renderFormData.value && Object.keys(renderFormData.value).length !== 0) {
    renderFormData.value.forEach((item) => {
      // 必填效验
      if (item.data.isMust) {
        rulesData[`${item.id}`] = [
          {
            required: true,
            message: item.data.placeholder,
            type: 'error',
            trigger: 'blur'
          }
        ]
      }
      // 如果input并且做了特殊效验 - 身份证、游戏、数字等  长度效验也是针对input的
      if (item.type === 'input') {
        const validatorFn =
          item.data.inputType !== 'none' ? rulesSet(item.data.inputType) : null
        const rulesList = {
          validator: validatorFn,
          message: item.data.errorPrompt || '请输入正确的值'
        }
        if (validatorFn && rulesData[`${item.id}`] !== undefined) {
          rulesData[`${item.id}`].push(rulesList)
        } else if (validatorFn && rulesData[`${item.id}`] === undefined) {
          rulesData[`${item.id}`] = [rulesList]
        }

        // 长度效验 有写组件自带最小值、最大值的效验 但有些没有 这里不做区分 只要有最大或者最小值全部进行效验
        if (item.data.minLength && rulesData[`${item.id}`] !== undefined) {
          rulesData[`${item.id}`].push({
            min: Number(item.data.minLength),
            message: '请输入正确的长度'
          })
        } else if (
          item.data.minLength &&
          rulesData[`${item.id}`] === undefined
        ) {
          rulesData[`${item.id}`] = [
            { min: Number(item.data.minLength), message: '请输入正确的长度' }
          ]
        }
        // 最大长度
        if (item.data.maxLength && rulesData[`${item.id}`] !== undefined) {
          rulesData[`${item.id}`].push({
            max: Number(item.data.maxLength),
            message: '请输入正确的长度'
          })
        } else if (
          item.data.maxLength &&
          rulesData[`${item.id}`] === undefined
        ) {
          rulesData[`${item.id}`] = [
            { max: Number(item.data.maxLength), message: '请输入正确的长度' }
          ]
        }
      }
      // 对选项的数量单独做个效果规则
      if (
        item.type === 'checkbox' ||
        (item.type === 'select' &&
          item.data.maxLength &&
          item.data.maxLength > 1)
      ) {
        // 最小长度效验
        if (item.data.minLength && rulesData[`${item.id}`] !== undefined) {
          rulesData[`${item.id}`].push({
            validator: (value) => {
              return value.length >= item.data.minLength
            },
            message: `请输入正确的选项, 最少应选${item.data.minLength}个`
          })
        } else if (
          item.data.minLength &&
          rulesData[`${item.id}`] === undefined
        ) {
          rulesData[`${item.id}`] = [
            {
              validator: (value) => {
                return value.length >= item.data.minLength
              },
              message: `请输入正确的选项, 最少应选${item.data.minLength}个`
            }
          ]
        }
        // 最大长度效验
        console.log(3333, item.data.maxLength, rulesData[`${item.id}`])
        if (item.data.maxLength && rulesData[`${item.id}`] !== undefined) {
          rulesData[`${item.id}`].push({
            validator: (value) => {
              console.log(value, value.length)
              return value.length <= item.data.maxLength
            },
            message: `请输入正确的选项, 最多应选${item.data.maxLength}个`
          })
        } else if (
          item.data.maxLength &&
          rulesData[`${item.id}`] === undefined
        ) {
          rulesData[`${item.id}`] = [
            {
              validator: (value) => {
                console.log(value, value.length)
                return value.length <= item.data.maxLength
              },
              message: `请输入正确的选项, 最多应选${item.data.maxLength}个`
            }
          ]
        }
      }
      // 如果是数字输入的话 处理一下小数位的效验
      if (
        item.type === 'number' &&
        item.data.floatNum &&
        rulesData[`${item.id}`] !== undefined
      ) {
        rulesData[`${item.id}`].push({
          validator: (value) => {
            return String(value).split('.').length >= 2
              ? String(value).split('.')[1].length <= item.data.floatNum
              : true
          },
          message: '请输入正确的长度'
        })
      }
      if (
        item.type === 'number' &&
        item.data.floatNum &&
        rulesData[`${item.id}`] === undefined
      ) {
        rulesData[`${item.id}`] = [
          {
            validator: (value) => {
              return String(value).split('.').length >= 2
                ? String(value).split('.')[1].length <= item.data.floatNum
                : true
            },
            message: '请输入正确的长度'
          }
        ]
      }
    })
  }
  console.log('效验规则：', rulesData)
  return rulesData
})

// 数字效验 包含 正数 负数 小数
const numberRule = /^-?\d+(\.\d+)?$/
// 整数类型 包含正、负整数和0
const intRule = /^-?\d+$/
// 浮点数类型 不包含正、负整数类型和0
const floatRule = /^-?(?!0)\d+(\.\d+)?$/
// url
const urlRule =
  /^(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9-]+\.[a-zA-Z]{2,}(?:\/[\w-]*)*\/?$/
// emil 邮箱
const emilRule = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
// 手机号效验
const phoneRule = /^1[3|4|5|6|7|8|9]\\d{9}$/
// 身份证
const idNumberRule18 =
  /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
const idNumberRule15 =
  /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/

// input的特殊效验规则
const rulesSet = (tg) => {
  let ruleResult: Function = null
  switch (tg) {
    case 'number':
      ruleResult = (value) => numberRule.test(value)
      break
    case 'int':
      ruleResult = (value) => intRule.test(value)
      break
    case 'float':
      ruleResult = (value) => floatRule.test(value)
      break
    case 'url':
      ruleResult = (value) => urlRule.test(value)
      break
    case 'emil':
      ruleResult = (value) => emilRule.test(value)
      break
    case 'phone':
      ruleResult = (value) => phoneRule.test(value)
      break
    case 'idNumber':
      ruleResult = (value) =>
        idNumberRule18.test(value) || idNumberRule15.test(value)
      break
  }
  return ruleResult
}

// 默认值处理 - 如果是checkbox 需要提前处理checkbox
const formDataInit = () => {
  if (renderFormData.value) {
    const baseFormData = {}
    renderFormData.value.forEach((item) => {
      if (item.type === 'checkbox' || item.type === 'dateArea') {
        baseFormData[`${item.id}`] = []
      }
      if (
        item.data.defaultValue !== '' &&
        item.data.defaultValue !== undefined
      ) {
        baseFormData[`${item.id}`] = item.data.defaultValue
      }
    })
    formData.value = baseFormData
  }
}
// 数据暂存提交
const cacheHandle = () => {
  const dom = formValidatorStatus.value
  if (dom.validate()) {
    const params = {
      id: 'SUBMIT_FORM_DATA',
      messageAuth: {
        tenant: 'tenant_hiss',
        currentUser: {
          userId: '1',
          userName: '张三',
          userGroups: ''
        }
      },
      palyload: {
        modelId: 'dc0af849c7f98019a6918debe03fcf56',
        page: 1,
        formData: formData.value
      }
    }
    // console.log(66776777, params)
  }
}
// 表单数据提交
const onSubmit = () => {
  const dom = formValidatorStatus.value
  console.log('提交数据', formData.value)
  if (dom.validate()) {
    const params = {
      id: 'SUBMIT_FORM_DATA',
      messageAuth: {
        tenant: 'tenant_hiss',
        currentUser: {
          userId: '1',
          userName: '张三',
          userGroups: ''
        }
      },
      palyload: {
        modelId: 'dc0af849c7f98019a6918debe03fcf56',
        formData: [{ page: 1, data: { ...formData.value } }]
      }
    }
    formDataes(params).then((res) => {
      if (res.code === 200) {
        MessagePlugin.success('数据保存成功')
      } else {
        MessagePlugin.error(res.msg || '数据提交出错了，请重试')
      }

      console.log(676, res)
    })
  }
}

// 获取表单数据获取
const getFromInteDataes = () => {
  const dom = formValidatorStatus.value
  console.log(formValidatorStatus.value)
  console.log(dom.validate())
  console.log('提交数据', formData.value)
  if (dom.validate()) {
    const params = {
      id: 'SUBMIT_FORM_DATA',
      messageAuth: {
        tenant: 'tenant_hiss',
        currentUser: {
          userId: '1',
          userName: '张三',
          userGroups: ''
        }
      },
      palyload: {
        modelId: '42',
        formData: [{ ...formData.value }]
      }
    }
    // formDataes(params).then(res => {
    //   const resData = res.data.res
    //   const context = JSON.parse(resData[0].context)
    //   BaseFormData.value = context.baseFormData
    //   renderFormData.value = context.formData.data
    //   console.log(676, context)
    // })
  }
  // { validateResult, firstError }
  // if (validateResult === true) {
  //   console.log(formData.value)
  //   MessagePlugin.success('提交成功')
  // } else {
  //   console.log('Validate Errors: ', firstError, validateResult)
  //   MessagePlugin.warning(firstError)
  // }
}

// 修改表单数据
const updateFromData = () => {
  const dom = formValidatorStatus.value
  console.log(formValidatorStatus.value)
  console.log(dom.validate())
  console.log('提交数据', formData.value)
  if (dom.validate()) {
    const params = {
      id: 'SUBMIT_FORM_DATA',
      messageAuth: {
        tenant: 'tenant_hiss',
        currentUser: {
          userId: '1',
          userName: '张三',
          userGroups: ''
        }
      },
      palyload: {
        modelId: '42',
        formData: [{ ...formData.value }]
      }
    }
    console.log(66776777, params)
    // formDataes(params).then(res => {
    //   const resData = res.data.res
    //   const context = JSON.parse(resData[0].context)
    //   BaseFormData.value = context.baseFormData
    //   renderFormData.value = context.formData.data
    //   console.log(676, context)
    // })
  }
}
// 表单重置
const onReset = () => {
  MessagePlugin.success('重置成功')
}
</script>
<style lang="less" scoped>
.renderFormCont {
  .t-form {
    width: 100%;
  }
  width: 80%;
  margin: 0 auto;
  // padding: 30px;
  border-radius: 4px;
  background-color: #fff;
  min-height: calc(100vh - 200px);
  .title {
    font-size: 22px;
    line-height: 50px;
    text-align: center;
    margin-bottom: 30px;
  }
  .formCont {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
